package morenoapp.util;

import java.awt.Color;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.jdesktop.application.Application;

/**
 *
 * @author dmitry.mamonov
 */
public class I18N {
    /**
     * Ресурсы приложения.
     */
    private static org.jdesktop.application.ResourceMap resourceMap =
            Application.getInstance(morenoapp.MorenoApp.class).getContext().getResourceMap(I18N.class);
    private static Map<String,String> fileResourcesMap = new HashMap<String,String>();

    /**
     * 
     * @param key
     * @param args
     * @return 
     */
    public static String getString(String key, String... args) {
        String result = resourceMap.getString(key, (Object[]) args);
        return result != null ? result : key;
    }

    /**
     * 
     * @param key
     * @return
     */
    public static Color getColor(String key) {
        return resourceMap.getColor(key);
    }

    /**
     * 
     * @param key
     * @return
     */
    public static String get(String key) {
        String result = resourceMap.getString(key);
        if (result==null && MorenoUtil.isDebug()){
            MorenoUtil.logKeyToFile(new File("missed_keys.txt"), key);
        }
        return result != null ? result : key;
    }

    public static String getResource(String key) {
        if (fileResourcesMap.containsKey(key) == false || MorenoUtil.isDebug()) {
            String text = "[ no resource with key | " + key + " ]";

            
            try {
                InputStream resourceInputStream = I18N.class.getResourceAsStream("resources/" + key);
                if (resourceInputStream != null) {
                    text = IOUtils.toString(new InputStreamReader(resourceInputStream, "utf-8"));
                }
            } catch (IOException ex) {
                Logger.getLogger(I18N.class.getName()).log(Level.SEVERE, null, ex);
            }
            fileResourcesMap.put(key, text);
        }
        return fileResourcesMap.get(key);
    }
}
